import {
  healthyList,
  addHealthy
} from '../../../utils/api'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    seleceId: [],
    isbtn: false,
    type:0,
    imgUrl: app.globalData.imgUrl,
    wxImgUrl: app.globalData.wxImgUrl,
    navBarHeight: '', //头高度
    statusBarHeight: '', //状态栏高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let navBarHeightinfo = app.publicFun.navBarHeightinfo()
    this.setData({
      navBarHeight: navBarHeightinfo[0],
      statusBarHeight: navBarHeightinfo[1]
    })
    if(options.type==1){
      this.setData({
        type:1
      })
    }
    healthyList({}).then(res => {
      res.forEach(e => {
        if (e.selected) {
          this.data.seleceId.push(e.id)
        }
      })
      this.setData({
        list: res,
        seleceId: this.data.seleceId
      })
    })
  },
  back() {
    wx.navigateBack({})
  },
  handlerCheck(event) {
    let e = event.currentTarget.dataset,
      _this = this;
    if (e.check) {
      let index = _this.data.seleceId.findIndex(item => item == e.id);
      _this.data.seleceId.splice(index, 1)
      _this.data.list[e.index].selected = false;
    } else {
      _this.data.seleceId.push(e.id);
      _this.data.list[e.index].selected = true;
    }
    _this.setData({
      seleceId: _this.data.seleceId,
      list: _this.data.list
    })
  },
  handlerAdd() {
    if (this.data.seleceId != '' && !this.data.isbtn) {
      this.setData({
        isbtn: true
      })
      wx.showLoading({
        title: '提交中',
      })
      addHealthy({
        diseaseIds: this.data.seleceId,
        userId: wx.getStorageSync('userid')
      }).then(res => {
        console.log(res)
        wx.hideLoading();
        if (res.code == undefined) {
          wx.showToast({
            title: '添加成功',
            icon: 'none'
          })
          let pages=getCurrentPages()
          let beforePage = pages[pages.length - 2];
          if(this.data.type==1){
            beforePage.gethealthy(1)
          }else{
            console.log(this.data.type)
            beforePage.getlist()
          }
           
          wx.navigateBack({})
        } else {
          this.setData({
            isbtn: false
          })
          wx.showToast({
            title: res.message,
            icon:'none'
          })
        }
      })
    }
  }
})